import "../tools/ajax.js"

import { getGoodsData } from "../modules/api.js";
import { cartRender } from "../modules/render.js";
import { setCartData } from "../modules/setLocal.js";
import setAllDataCheck from "../modules/setAllDataCheck.js";
import sum from "../modules/sum.js";

let goods = localStorage.getItem("goods")
goods = goods ? JSON.parse(goods) : [];

const tbody = document.querySelector("tbody");
const allCheck = document.querySelector(".allCheck");
const delCheck = document.querySelector(".delCheck");

// let obj = null;
;(async function(){
    const data = await getGoodsData()
    cartRender(tbody, data, goods);
    // obj = data;
})();

// 选中状态
tbody.onchange = function(eve){
    const ele = eve.target
    if(ele.className.includes("check")){
        const id = ele.parentNode.parentNode.getAttribute("myid");

        setCartData(goods, id, (i)=>{
            goods[i].check = ele.checked;
        });

        // 判断是否需要全选
        allCheck.checked = goods.every(val=>val.check);
    }
}

// 修改数量
tbody.oninput = function(eve){
    const ele = eve.target;
    if(ele.className.includes("num")){
        const tr = ele.parentNode.parentNode;
        const id = tr.getAttribute("myid");

        setCartData(goods, id, (i)=>{
            goods[i].num = ele.value-0;
            // 计算小计
            tr.querySelector(".count").innerHTML = ele.value * goods[i].price
        });

        // 计算总价和总数量
        sum(goods);
    }
}

// 删除商品
tbody.onclick = function(eve){
    const ele = eve.target;
    if(ele.className.includes("del")){
        const id = ele.parentNode.getAttribute("myid");
        ele.parentNode.remove();

        setCartData(goods, id, (i)=>{
            goods.splice(i, 1);
        });

        // 判断是否需要全选
        allCheck.checked = goods.length < 1 ? false : goods.every(val=>val.check);

        // 计算总价和总数量
        sum(goods)
    }
}

// 判断是否需要全选
allCheck.checked = goods.length < 1 ? false : goods.every(val=>val.check);

// 全选状态修改时，影响单个商品的选中
allCheck.onchange = function(){
    setAllDataCheck(goods, this.checked);
}

// 计算总价和总数量
sum(goods);

// 删除选中
delCheck.onclick = function(){
    // 从数据中删除，并更新本地存储
    goods = goods.filter(val=>!val.check);
    localStorage.setItem("goods",JSON.stringify(goods));

    // cartRender(tbody, obj, goods);

    // 删除选中商品的DOM结构
    const checks = document.querySelectorAll(".check");
    [...checks].forEach(val=>{
        if(val.checked){
            val.parentNode.parentNode.remove();
        }
    })
}